<?php

namespace catchAdmin\pc\model;

use catchAdmin\model\Notice;
use catcher\exceptions\AlertErrorException;

class WithdrawIncome extends \catchAdmin\model\WechatUserBalance
{

    public $name = 'wechat_user_balance';


    /**
     * 审核
     */
    public function audit($param)
    {
        $this->startTrans();

        $withdraw_msg = $this
            ->where('id', $param['id'])
            ->where('balance_type_2', 302)
            ->where('balance_status', 1)
            ->find();

        if (empty($withdraw_msg)) {
            throw new AlertErrorException();
        }

        // 1.保存审核状态
        $balance_msg = $this->saveDataCC([
            'id'                  => $param['id'],
            'balance_status'      => $param['balance_status'],
            'balance_status_note' => $param['balance_status_note'] ?? '',
            'balance_status_time' => time(),
        ]);

        // 发消息
        (new Notice())->saveDataCC([
            // 提现审核——审核结果
            'notice_type'    => 2,
            'title'          => $balance_msg['balance_status_name'],
            'content'        => $balance_msg['balance_status_note'],
            'wechat_user_id' => $balance_msg['wechat_user_id'],
        ]);

        // 2.未通过
        if ($withdraw_msg->balance_status == 3) {
            (new \catchAdmin\model\WechatUserBalance())->saveWechatUserBalance([
                'wechat_user_id' => $withdraw_msg['wechat_user_id'],
                'balance_type'   => 3,
                'balance_type_2' => 303,
                'num'            => $withdraw_msg['num'],
                'out_trade_no'   => time() . rand(100000, 999999),
            ]);
        }

        $this->commit();

        return 1;
    }


    ############################ 显示 ########################

    public function indexData($param)
    {
        $app = $this
            ->where('balance_type', 3)
            ->where('balance_type_2', 302)
            ->with(['wechatUser']);

        return $this->indexDataPcCC($param, $app);
    }
}
